import React, { useEffect, useState } from "react";
import { Menu } from "antd";
import "./index.less";
import type { RouteModal } from "./routes";
import routes from "./routes";
import { Outlet, useNavigate, useLocation } from "react-router-dom";

const menuItem = (item: RouteModal) => {
  const { name, path, children } = item;
  if (!path) {
    return null;
  }
  if (children) {
    return (
      <Menu.SubMenu title={name} key={path}>
        {children.map((childItem) => {
          return menuItem(childItem);
        })}
      </Menu.SubMenu>
    );
  }
  return <Menu.Item key={path}>{name}</Menu.Item>;
};
export default () => {
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const [keys, setKeys] = useState(["/form/select"]);
  const [openKey, setOpenKey] = useState(["/form"]);
  useEffect(() => {
    setKeys([pathname]);
    const pathOpenKeys = pathname.split("/");
    const openKeys = pathOpenKeys.map((path) => {
      return "/" + path;
    });
    setOpenKey(openKeys);
  }, [pathname]);
  return (
    <div className="layout">
      <Menu
        className="menu"
        selectedKeys={keys}
        openKeys={openKey}
        onOpenChange={(openKeys) => {
          setOpenKey(openKeys);
        }}
        onSelect={(e) => {
          navigate(e.key);
        }}
        mode={"inline"}
        theme="dark"
      >
        {routes.map((item) => {
          return menuItem(item);
        })}
      </Menu>
      <div className="body">
        <Outlet />
      </div>
    </div>
  );
};
